<?php
/**
 * Created by PhpStorm.
 * User: zhongbaitong
 * Date: 2020/1/14
 * Time: 10:10
 */

namespace app\forum\home;

use app\common\controller\ApiBase;
use app\forum\model\Post as PostModel;
use app\forum\model\PostLike;

class Posts extends ApiBase
{
    /**
     * 帖子列表
     * @return \think\response\Json
     * @throws \app\common\exception\ApiError
     */
    public function lists(){
        $input = $this->getInput("",1);

        $data = PostModel::getLists($input);

        return $this->apiReturn(compact('data'));
    }

    /**
     * 帖子详情
     * @return \think\response\Json
     * @throws \app\common\exception\ApiError
     * @throws \think\Exception\DbException
     */
    public function detail(){
        $input = $this->getInput("post_id",1);

        $data = PostModel::getInfo($input);

        return $this->apiReturn(compact("data"));
    }

    /**
     * 发表帖子
     * @params images = [
     *    ["path" => "test image 111"],
     *    ["path" => "test image 222"],
     * ];
     * @return \think\response\Json
     * @throws \app\common\exception\ApiError
     */
    public function create(){
        $input = $this->getInput("post_type,content",1);
        $post = PostModel::create($input);
        // 图片贴
        if($post->post_type == 1){
            if(!isset($input["images"]))
                return $this->apiError("post_type == 1 && images 参数必须！");

            $images = is_array($input["images"]) ? $input["images"]
                : json_decode(htmlspecialchars_decode($input["images"]),1);

            $post->images()->saveAll($images);
        }

        return $this->apiReturn(["data" => $post]);
    }

    // 删除帖子
    public function delete(){
        $post_id = $this->request->param("post_id");

        $post = PostModel::get($post_id);

        if(!$post || $post->user_id != $this->getAuthorizeUID())
            return $this->apiError("帖子不存在或权限不足！");

        $post->delete();

        return $this->apiSuccess("删除成功！");
    }

    // 点赞
    public function likeHandle(){
        $post_id = $this->request->param("post_id");
        $user_id = $this->getAuthorizeUID();

        if(!PostModel::get($post_id))
            return $this->apiError("帖子不存在！");

        $data = PostLike::handle(compact("user_id","post_id"));

        return $this->apiReturn($data);
    }
}